<template>
  <Card>
    <div class="searchBox">
      <Form ref="searchForm" :label-width="90" :model="searchForm" class="search-formApply" inline>
        <Form-item label="单号：" prop="number">
          <Input v-model="searchForm.number" clearable placeholder="支持模糊搜索" style="width: 200px" type="text"/>
        </Form-item>
        <Form-item label="状态：" prop="status">
          <Select v-model="searchForm.status" style="width: 200px">
            <Option :key="-1" :value="-1">全部</Option>
            <Option value="1">待提交</Option>
            <Option value="2">待审核</Option>
            <Option value="4">未通过</Option>
            <Option value="0">已结束</Option>
          </Select>
        </Form-item>
        <Form-item label="车牌号：" prop="license_plate_num">
          <Input
            v-model="searchForm.license_plate_num"
            clearable
            placeholder="支持模糊搜索"
            style="width: 200px"
            type="text"/>
        </Form-item>
        <Form-item label="日期范围：" prop="date">
          <DatePicker
            v-model="searchForm.date"
            placeholder="请选择日期范围"
            placement="bottom-start"
            style="width: 200px"
            type="daterange"></DatePicker>
        </Form-item>
        <Form-item style="margin-left:-90px;">
          <Button icon="md-search" type="primary" @click="handleSearch">搜索</Button>
          <Button @click="handleReset">重置</Button>
        </Form-item>
      </Form>
    </div>
    <div class="btns">
      <Button icon="ios-add" target="_self" type="primary" @click="toAdd">添加申请</Button>
      <Button icon="md-trash" type="error" @click="delAll">删除</Button>
    </div>
    <div class="table">
      <Row v-if="displaySelected">
        <Alert show-icon>
          已选择
          <span class="select-count">{{ selectCount }}</span> 项
          <a class="select-clear" @click="clearSelectAll">清空</a>
        </Alert>
      </Row>
      <Row>
        <Table
          ref="table"
          :columns="columns"
          :data="data"
          :loading="loading"
          border
          size="small"
          @on-selection-change="showSelect">
          <template slot="action" slot-scope="{ row }">
            <Button ghost style="color:#2d8cf0;font-size: 12px;" type="text" @click="preview(row)">查看</Button>
            <Divider type="vertical"/>
            <Button
              :disabled="row.editBtnDisabled"
              :style="row.editBtnStyle"
              ghost
              type="text"
              @click="edit(row.id)">编辑
            </Button>
            <Divider type="vertical"/>
            <Button
              :disabled="row.delBtnDisabled"
              :style="row.delBtnStyle"
              ghost
              type="text"
              @click="del(row)">删除
            </Button>
          </template>
        </Table>
      </Row>
      <Row class="page" justify="end" type="flex">
        <Page
          :current="searchForm.pageNumber"
          :page-size="searchForm.pageSize"
          :total="total"
          show-total
          @on-change="changePage"/>
      </Row>
    </div>
    <Modal
      v-model="modalApplyVisible"
      :mask-closable="false"
      :styles="{top: '20px'}"
      :title="modalApplyTitle"
      :width="900">
      <Form ref="formApply" :label-width="110" :model="formApply" :rules="formApplyValidate" label-position="right">
        <Alert v-if="openErrorAlert" show-icon type="error">
          审核意见
          <span slot="desc">{{ formApply.reason }}</span>
        </Alert>
        <Divider v-if="openErrorAlert"/>
        <Row>
          <Col span="12">
          <FormItem v-if="isShowNumber" label="单号：" prop="number">
            <Input v-model="formApply.number" readonly type="text"/>
          </FormItem>
          </Col>
          <div v-if="modalApplyType < 2">
            <Col span="12">
            <FormItem label="车辆线路：" prop="line">
              <Select v-model="formApply.line" clearable placeholder="选择线路">
                <Option v-for="item in lines" :key="item.value" :value="item.value">{{ item.label }}</Option>
              </Select>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="车牌号：" prop="license_plate_num">
              <Select v-model="formApply.license_plate_num" placeholder="选择车牌号">
                <Option v-for="item in licensePlateNumList" :key="item.value" :value="item.value">{{ item.label }}
                </Option>
              </Select>
            </FormItem>
            </Col>
          </div>
          <div v-else>
            <Col span="12">
            <FormItem label="车辆线路：" prop="line">
              <Input v-model="formApply.line" :readonly="isReadonly" type="text"/>
            </FormItem>
            </Col>
            <Col span="12">
            <FormItem label="车牌号：" prop="license_plate_num">
              <Input v-model="formApply.license_plate_num" :readonly="isReadonly" type="text"/>
            </FormItem>
            </Col>
          </div>
          <Col span="12">
          <FormItem label="日期：" prop="date">
            <DatePicker
              v-model="formApply.date"
              :clearable="false"
              :readonly="isReadonly"
              format="yyyy-MM-dd"
              placeholder="选择时间"
              type="date"></DatePicker>
          </FormItem>
          </Col>
          <Col span="12">
          <FormItem label="驾驶员：" prop="driver">
            <Input v-model="formApply.driver" type="text"/>
          </FormItem>
          </Col>
          <Col span="24">
          <FormItem label="维修情况：" prop="description">
            <Input
              v-model="formApply.description"
              :autosize="{minRows: 4,maxRows: 5}"
              :readonly="isReadonly"
              :rows="4"
              placeholder="请输入..."
              type="textarea"></Input>
          </FormItem>
          </Col>
          <Col span="24">
          <FormItem label="上传照片：" prop="driverUploadFile">
            <upload-pic-thumb-multiple
              ref="driverUploadFile"
              :params="{saveDir: 'mrApply', type: 'pic'}"
              :readonly="isReadonly"
              @on-change="formApply.driverUploadFile=$event"></upload-pic-thumb-multiple>
            <div style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;">
              1、支持jpg、jpeg、png格式的图片，最大不超过600KB
            </div>
            <div style="color:#ea856b;font-size: 12px;line-height: 20px;height: 20px;">2、请确保上传完毕之后再提交保存</div>
          </FormItem>
          </Col>
        </Row>
        <div v-if="isShowAuditRecord">
          <Divider>审核记录</Divider>
          <div id="auditRecord">
            <div v-for="item of auditRecord" :key="item.id" class="stepCard">
              <div>
                <p>
                  <Icon size="30" type="md-contact"/>
                  {{ item.nodeName }}
                </p>
                <span>时间：{{ item.created_at }}&nbsp;&nbsp;&nbsp;&nbsp;操作：{{ item.resultName }}</span>
                <span v-if="item.reason !== null && item.reason !== ''">退回理由：{{ item.reason }}</span>
              </div>
              <div>
                <p>单据编号：{{ item.number }}</p>
                <div v-if="item.signature !== null">
                  <p>签名：</p><img :src="item.signature" alt="">
                </div>
              </div>
              <div></div>
            </div>
          </div>
        </div>
      </Form>
      <div slot="footer">
        <Button v-if="isShowCancelBtn" type="text" @click="handleApplyCancel">取消</Button>
        <Button
          v-if="isShowSaveBtn"
          :loading="saveApplyLoading"
          type="info"
          @click="handleApplySubmit('save')">保存草稿
        </Button>
        <Button v-if="isShowSaveSubmitBtn" type="primary" @click="handleApplySubmit('submit')">保存并提交审核</Button>
      </div>
    </Modal>
    <!--    签名窗口-->
    <Modal v-model="signModal" :mask-closable="false" title="请签字确认" width="600">
      <VueSignaturePad
        id="signature"
        ref="signaturePad"
        :options="{onBegin: () => {$refs.signaturePad.resizeCanvas()}}"
        height="300px"
        width="100%"/>
      <div slot="footer">
        <Button icon="md-undo" type="dashed" @click="undo">撤销</Button>
        <Button icon="md-refresh" @click="refresh">清除</Button>
        <Button :loading="signLoading" icon="md-checkmark" type="primary" @click="save">完成</Button>
      </div>
    </Modal>
  </Card>
</template>
<script>
import moment from 'moment'
import {licensePlateNumList} from '../../api/bus'
import UploadPicThumbMultiple from '../my-components/upload-pic-thumb-multiple'
import {applyList, destroyApply, editAppply, storeApply, updateApply,} from '../../api/mrApply'

export default {
  components: {
    UploadPicThumbMultiple,
  },
  data() {
    return {
      isShowCancelBtn: true,
      isShowSaveBtn: true,
      isShowSaveSubmitBtn: true,
      isShowAuditRecord: false,
      nodeKey: '',
      openErrorAlert: false,
      isDisabled: false,
      isReadonly: false,
      isShowNumber: false,
      total: 0,
      selectCount: 0,
      selectList: [],
      searchForm: {
        number: '',
        date: [null, null],
        license_plate_num: '',
        status: -1,
        pageNumber: 1,
        pageSize: 10,
      },
      reasonForm: {
        reason: '',
      },
      formApply: {
        nodeType: '',
        nodeKey: '',
        number: '',
        line: '',
        license_plate_num: '',
        driver: '', // 默认当前用户
        user_id: this.$store.getters.user.id, // 默认当前用户ID
        date: moment().format('YYYY-MM-DD'), //默认今天
        description: '',
        driverUploadFile: [],
      },
      formCost: {
        line: '',
        license_plate_num: '',
        driver: this.$store.getters.user.name, // 默认当前用户
        date: moment().format('YYYY-MM-DD'), //默认今天
        description: '',
      },
      loading: false,
      columns: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
          fixed: 'left',
        },
        {
          type: 'index',
          width: 60,
          align: 'center',
          fixed: 'left',
        },
        {
          title: '单号',
          key: 'number',
          width: 150,
          align: 'left',
        },
        {
          title: '单据日期',
          key: 'date',
          width: 150,
          align: 'center',
        },
        {
          title: '车牌号',
          key: 'license_plate_num',
          width: 120,
          align: 'center',
        },
        {
          title: '线路',
          key: 'line',
          width: 120,
          align: 'center',
        },
        {
          title: '驾驶员',
          key: 'driver',
          width: 120,
          align: 'left',
        },
        {
          title: '发起人',
          key: 'user_name',
          width: 120,
          align: 'left',
        },
        {
          title: '当前节点',
          key: 'current_node',
          width: 200,
          align: 'center',
        },
        {
          title: '状态',
          key: 'current_status',
          width: 200,
          align: 'center',
        },
        {
          title: '维修情况',
          key: 'description',
          width: 200,
          align: 'left',
        },
        {
          title: '创建时间',
          key: 'created_at',
          width: 170,
          align: 'right',
        },
        {
          title: '操作',
          slot: 'action',
          width: 230,
          fixed: 'right',
          align: 'center',
        },
      ],
      data: [],
      costData: [],
      submitApplyLoading: false,
      saveApplyLoading: false,
      submitCostLoading: false,
      modalApplyType: 0,
      modalCostType: 0,
      modalApplyVisible: false,
      modalCostVisible: false,
      formApplyValidate: {
        line: [
          {
            required: true,
            message: '车辆线路不能为空',
            trigger: 'change',
            type: 'number',
          },
        ],
        license_plate_num: [
          {
            required: true,
            message: '车牌号不能为空',
            trigger: 'change',
            type: 'string',
          },
        ],
        // date: [{required: true, message: "时间不能为空", trigger: "blur", type: 'date'}],
      },
      formCostValidate: {
        license_plate_num: [
          {required: true, message: '车牌号不能为空', trigger: 'blur'},
        ],
      },
      modalApplyTitle: '',
      modalCostTitle: '',
      licensePlateNumList: [],
      lines: [],
      disableNodeId: true,
      displaySelected: true,
      auditRecord: [],
      signModal: false,
      signLoading: false,
    }
  },
  mounted() {
    this.init()
    this.getLinesArray()
  },
  methods: {
    async getLinesArray() {
      this.lines = await this.getLines()
    },
    changePage(v) {
      this.searchForm.pageNumber = v
      this.getMrApplyList()
      this.clearSelectAll()
    },
    clearSelectAll() {
      this.$refs.table.selectAll(false)
    },
    del(row) {
      this.$Modal.confirm({
        title: '确认删除',
        loading: true,
        content: '您确认要删除此条数据吗？',
        onOk: () => {
          const ids = row.id
          // 批量删除
          destroyApply(ids).then((res) => {
            this.$Modal.remove()
            if (res.data === true) {
              this.$Message.success(res.message)
              this.getMrApplyList()
            } else {
              this.$Message.error(res.message)
            }
          })
        },
      })
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未选择要删除的数据')
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        loading: true,
        content: '您确认要删除所选的 ' + this.selectCount + ' 条数据？',
        onOk: () => {
          let ids = ''
          this.selectList.forEach(function (e) {
            ids += e.id + ','
          })
          ids = ids.substring(0, ids.length - 1)
          // 批量删除
          destroyApply(ids).then((res) => {
            this.$Modal.remove()
            if (res.data === true) {
              this.$Message.success(res.message)
              this.getMrApplyList()
            } else {
              this.$Message.error(res.message)
            }
          })
        },
      })
    },
    edit(id) {
      this.isShowAuditRecord = true
      this.isShowCancelBtn = true
      this.isShowSaveBtn = true
      this.isShowSaveSubmitBtn = true
      this.modalApplyType = 1
      this.modalApplyTitle = '编辑'
      editAppply(id).then((res) => {
        this.isShowNumber = true
        this.formApply = res.data
        this.formApply.driver = res.data.user_name
        this.openErrorAlert =
          this.formApply.reason != null && this.formApply.reason !== ''
        this.auditRecord = res.data.auditRecord
        // 先清空上传列表，再显示已上传图片
        this.$refs.driverUploadFile.handleClearFiles()
        this.$refs.driverUploadFile.setData(res.data.apply_file.driver)
        this.isReadonly = false
        this.modalApplyVisible = true
      })
    },
    getLicensePlateNumList() {
      licensePlateNumList().then((res) => {
        const data = []
        res.data.forEach(function (e, i) {
          data.push({
            label: e,
            value: e,
          })
        })
        this.licensePlateNumList = data
      })
    },
    getMrApplyList() {
      this.loading = true
      this.clearSelectAll()
      applyList(this.searchForm).then((res) => {
        this.loading = false
        if (res.data) {
          this.data = res.data.mrApplyRecord
          this.total = res.data.count
        }
      })
    },
    handleApplyCancel() {
      this.modalApplyVisible = false
      this.$refs.formApply.resetFields()
    },
    handleApplySubmit(e) {
      this.$refs.formApply.validate((valid) => {
        if (valid) {
          this.submitApplyLoading = e === 'submit'
          this.saveApplyLoading = e === 'save'
          this.formApply.nodeType = e
          this.formApply.nodeKey = this.nodeKey
          if (e === 'save') {
            this.toAuditApply('')
          } else {
            this.$refs.signaturePad.clearSignature()
            this.signLoading = false
            this.signModal = true
          }
        }
      })
    },
    handleReset() {
      this.$refs.searchForm.resetFields()
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getMrApplyList()
    },
    handleSearch() {
      this.searchForm.pageNumber = 1
      this.searchForm.pageSize = 10
      this.getMrApplyList()
    },
    init() {
      this.nodeKey =
        this.$store.getters.user.roleName.indexOf('维修-司机') !== -1
          ? 'wr_apply_driver'
          : 'wr_apply_driver_leader'
      this.getLicensePlateNumList()
      this.getMrApplyList()
    },
    preview(row) {
      this.isShowCancelBtn = false
      this.isShowSaveBtn = false
      this.isShowSaveSubmitBtn = false
      this.isShowAuditRecord = true
      this.modalApplyType = 2
      this.modalApplyTitle = '查看'
      editAppply(row.id).then((res) => {
        this.isShowNumber = true
        this.formApply = res.data
        this.formApply.driver = res.data.user_name
        this.openErrorAlert =
          this.formApply.reason != null && this.formApply.reason !== ''
        this.auditRecord = res.data.auditRecord
        // 先清空上传列表，再显示已上传图片
        this.$refs.driverUploadFile.handleClearFiles()
        this.$refs.driverUploadFile.setData(res.data.apply_file.driver)
        // 字段只读
        this.isReadonly = true
        this.isDisabled = true
        this.modalApplyVisible = true
      })
    },
    showSelect(e) {
      this.selectList = e
      this.selectCount = e.length
    },
    toAdd() {
      this.isShowAuditRecord = false
      this.isShowNumber = false
      this.openErrorAlert = false
      this.openErrorAlert = false
      this.isShowCancelBtn = true
      this.isShowSaveBtn = true
      this.isShowSaveSubmitBtn = true
      this.modalApplyType = 0
      this.modalApplyTitle = '添加'
      this.$refs.formApply.resetFields()
      this.$refs.driverUploadFile.handleClearFiles()
      this.submitApplyLoading = this.saveAndSubmitApplyLoading = false
      delete this.formApply.id
      this.isReadonly = false
      this.modalApplyVisible = true
    },
    undo() {
      this.$refs.signaturePad.undoSignature()
    },
    refresh() {
      this.$refs.signaturePad.clearSignature()
    },
    save() {
      this.signLoading = true
      const {isEmpty, data} = this.$refs.signaturePad.saveSignature()
      if (!isEmpty) {
        this.toAuditApply(data)
      } else {
        this.$Message.success('签名为空')
      }
    },
    toAuditApply(data) {
      this.formApply.sign = data
      if (this.modalApplyType === 0) {
        delete this.formApply.id
        storeApply(this.formApply).then((res) => {
          this.submitApplyLoading = this.saveApplyLoading = false
          this.signLoading = false
          this.signModal = false
          if (res.data) {
            this.$Message.success(res.message)
            this.getMrApplyList()
            this.modalApplyVisible = false
          } else {
            this.$Message.error(res.message)
          }
        })
      } else if (this.modalApplyType === 1) {
        updateApply(this.formApply, this.formApply.id).then((res) => {
          this.submitApplyLoading = this.saveApplyLoading = false
          this.signLoading = false
          this.signModal = false
          if (res.data) {
            this.$Message.success('更新成功')
            this.getMrApplyList()
            this.modalApplyVisible = false
          } else {
            this.$Message.error(res.message)
          }
        })
      } else {
      }
    },
  },
}
</script>
<style scoped>
/*去除竖行分割线margin*/
.ivu-table-row .ivu-divider-vertical {
  margin: 0;
}

/* 审核记录 */
#auditRecord {
  padding: 0 2%;
}

#auditRecord .title {
  font-family: "Font Awesome 5 Pro Solid", "Font Awesome 5 Pro Regular",
  "Font Awesome 5 Pro", serif;
  font-weight: 900;
  font-style: normal;
  font-size: 16px;
  margin-top: 15px;
}

#auditRecord .stepCard {
  border: 1px solid rgba(215, 232, 244, 1);
  background-color: #f7fbfe;
  height: 120px;
  width: 90%;
  padding: 0 1%;
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
  position: relative;
  left: 35px;
}

#auditRecord .stepCard > div:first-child {
  font-family: "微软雅黑", serif;
  font-weight: 400;
  font-size: 14px;
  color: #666;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

#auditRecord .stepCard > div:first-child > span {
  margin-top: 10px;
  color: #999;
}

#auditRecord .stepCard > div:nth-child(2) {
  margin-top: 20px;
  color: #666;
}

#auditRecord .stepCard > div:nth-child(2) > div {
  height: 70px;
  width: 120px;
  display: flex;
  white-space: nowrap;
  justify-content: space-between;
  line-height: 100px;
}

#auditRecord .stepCard > div:nth-child(2) > div img {
  width: 100%;
  height: 100%;
}

#auditRecord .stepCard > div:last-child {
  position: absolute;
  width: 15px;
  height: 15px;
  border-radius: 50%;
  border: 1px solid #9ed1f5;
  left: -30px;
  top: 52px;
}

#auditRecord .pointIndex {
  background-color: #9ed1f5;
}

#signature {
  border: double 2px transparent;
  border-radius: 2px;
  background-image: linear-gradient(white, white),
  radial-gradient(circle at top left, #808695, #808695);
  background-origin: border-box;
  background-clip: content-box, border-box;
}
</style>
